package com.center.fragment;


import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.anime.activity.AnimePlayActivity;
import com.anime.model.ViewModelSwitch;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cartoon.activity.KKCarttonReadingActivity;
import com.cartoon.activity.LRYCarttonReadingActivity;
import com.cartoon.model.CartoonDataViewModel;
import com.center.R;
import com.center.activity.LoginActivity;
import com.center.activity.ShareActivity;
import com.center.adapter.AnimeHistoryAdapter;
import com.center.adapter.CarttonHistoryAdapter;
import com.center.adapter.FunctionsAdapter;
import com.center.databinding.CenterFrgmentBinding;
import com.center.dialog.SystemDialog;
import com.center.model.AnimeHistoryModel;
import com.center.model.CarttonHistoryModel;
import com.center.model.ViewModelQQLogin;
import com.center.util.Util;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.open.log.SLog;
import com.tencent.tauth.DefaultUiListener;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;

import anime.play.room.AnimePlayHistoryModel;
import anime.play.room.AnimePlayHistoryViewModel;
import base.QFragment;
import cartoon.room.read.room.CartoonReadHistoryModel;
import cartoon.room.read.room.CartoonReadHistoryViewModel;
import constant.AppConstants;
import model.CarttonKKHistrory;

public class CenterFragment extends QFragment<CenterFrgmentBinding> {
    private static Tencent mTencent;

    private ViewModelQQLogin viewModelQQLogin;
    private FunctionsAdapter functionAdapter;
    private ArrayList<String> list = new ArrayList<>();
    private AnimePlayHistoryViewModel animeviewModel;
    private AnimeHistoryAdapter animeHistoryAdapter;


    private LinkedHashMap<String, AnimeHistoryModel> animeMap = new LinkedHashMap<>();
    private List<AnimeHistoryModel> animeList = new ArrayList<AnimeHistoryModel>();


    private LinkedHashMap<String, CarttonHistoryModel> carttonMap = new LinkedHashMap<>();
    private List<CarttonHistoryModel> carttonList = new ArrayList<CarttonHistoryModel>();


    private int historytype = 0;
    private CartoonReadHistoryViewModel cartoonViewModel;
    private CarttonHistoryAdapter carttonHistoryAdapter;
    private ViewModelSwitch viewSearchModel;

    @Override
    public int getLayoutRes() {
        return R.layout.center_frgment;
    }

    @Override
    public void initView() {
        viewModelQQLogin = ViewModelQQLogin.getInstance();


        //不加这个会加载不出来
        Tencent.setIsPermissionGranted(true);
        mTencent = Tencent.createInstance(AppConstants.APP_ID, getActivity());

        animeviewModel = new ViewModelProvider(this).get(AnimePlayHistoryViewModel.class);

        cartoonViewModel = new ViewModelProvider(this).get(CartoonReadHistoryViewModel.class);
    }

    @Override
    public void initData() {

        viewSearchModel = new ViewModelProvider(this).get(ViewModelSwitch.class);

        //这里是判断 如果是之前有登录过 token没过期就走这里了  如果过期了点击登录哪里会跳转Activity登录
        getTokenLogin();
        list.clear();
        list.add("分享");
        list.add("QQ群");
        list.add("赞助");
        list.add("设置");

        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 4, GridLayoutManager.VERTICAL, false);
        binding.rvFunction.setLayoutManager(layoutManager);
        functionAdapter = new FunctionsAdapter(R.layout.function_item, list);
        binding.rvFunction.setAdapter(functionAdapter);


        LinearLayoutManager animeLaymanage = new LinearLayoutManager(getActivity());
        animeLaymanage.setOrientation(LinearLayoutManager.HORIZONTAL);
        binding.rvAnimeHistory.setLayoutManager(animeLaymanage);
        animeHistoryAdapter = new AnimeHistoryAdapter(R.layout.anime_history_item, null);
        binding.rvAnimeHistory.setAdapter(animeHistoryAdapter);



        LinearLayoutManager carttonKKLmanage = new LinearLayoutManager(getActivity());
        carttonKKLmanage.setOrientation(LinearLayoutManager.HORIZONTAL);
        binding.rvCarttonHistory.setLayoutManager(carttonKKLmanage);
        carttonHistoryAdapter = new CarttonHistoryAdapter(R.layout.anime_history_item, null);
        binding.rvCarttonHistory.setAdapter(carttonHistoryAdapter);


        binding.rvAnimeHistory.setVisibility(View.VISIBLE);
        binding.rvCarttonHistory.setVisibility(View.GONE);
    }


    @Override
    public void initListener() {

        viewSearchModel.getSwitch().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer index) {

                int anInt = SPStaticUtils.getInt(AppConstants.SWITCHKEY, index);
                if (anInt == 1) {
                    binding.ivSwitch.setImageResource(R.mipmap.sw1);
                } else if (anInt == 2) {
                    binding.ivSwitch.setImageResource(R.mipmap.sw2);
                }


            }
        });


        binding.ivSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int anInt = SPStaticUtils.getInt(AppConstants.SWITCHKEY, 1);
                if (anInt == 1) {
                    SPStaticUtils.put(AppConstants.SWITCHKEY, 2);
                    viewSearchModel.getSwitch().postValue(2);
                } else if (anInt == 2) {
                    SPStaticUtils.put(AppConstants.SWITCHKEY, 1);
                    viewSearchModel.getSwitch().postValue(1);
                }

            }
        });

        binding.tvHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (historytype < 2) {
                    historytype++;
                } else {
                    historytype = 0;
                }
                if (historytype == 0) {
                    binding.tvHistory.setText("视频历史 (点击文字切换不同历史)");

                    binding.rvAnimeHistory.setVisibility(View.VISIBLE);
                    binding.rvCarttonHistory.setVisibility(View.GONE);
                } else if (historytype == 1) {
                    binding.tvHistory.setText("漫画历史 (点击文字切换不同历史)");

                    binding.rvAnimeHistory.setVisibility(View.GONE);
                    binding.rvCarttonHistory.setVisibility(View.VISIBLE);
                } else {
                    binding.tvHistory.setText("小说历史 (点击文字切换不同历史)");

                    binding.rvAnimeHistory.setVisibility(View.GONE);
                    binding.rvCarttonHistory.setVisibility(View.GONE);
                }
            }
        });


        cartoonViewModel.getAllSLive().observe(this, new Observer<List<CartoonReadHistoryModel>>() {
            @Override
            public void onChanged(List<CartoonReadHistoryModel> cartoonReadHistoryModels) {

                LogUtils.d("看看数据.."+cartoonReadHistoryModels);

                carttonList.clear();

                for (int i = 0; i < cartoonReadHistoryModels.size(); i++) {


                    if (cartoonReadHistoryModels.get(i).getType() == 1) {

                        LogUtils.d("看看数据A.."+cartoonReadHistoryModels);
                        carttonMap.remove(cartoonReadHistoryModels.get(i).getName());
                        carttonMap.put(cartoonReadHistoryModels.get(i).getName(),
                                new CarttonHistoryModel(
                                        cartoonReadHistoryModels.get(i).getName(),
                                        cartoonReadHistoryModels.get(i).getTitle(),
                                        cartoonReadHistoryModels.get(i).getPic(),
                                        cartoonReadHistoryModels.get(i).getType(),
                                        cartoonReadHistoryModels.get(i).getLryid(),
                                        null));
                    } else if (cartoonReadHistoryModels.get(i).getType() == 2) {

                        Type listType = new TypeToken<List<CarttonKKHistrory>>() {
                        }.getType();
                        List<CarttonKKHistrory> kkList = GsonUtils.fromJson(cartoonReadHistoryModels.get(i).getKklist(), listType);


                        carttonMap.remove(cartoonReadHistoryModels.get(i).getName());
                        carttonMap.put(cartoonReadHistoryModels.get(i).getName(),
                                new CarttonHistoryModel(
                                        cartoonReadHistoryModels.get(i).getName(),
                                        cartoonReadHistoryModels.get(i).getTitle(),
                                        cartoonReadHistoryModels.get(i).getPic(),
                                        cartoonReadHistoryModels.get(i).getType(),
                                        cartoonReadHistoryModels.get(i).getKkid(),
                                        kkList));


                    }


                }


                for (LinkedHashMap.Entry<String, CarttonHistoryModel> entry : carttonMap.entrySet()) {
                    LogUtils.d("看看数据B.."+entry.getValue().getName(),entry.getValue().getPic());
                    if (entry.getValue().getTitleName() != null && entry.getValue().getPic() != null) {

                        LogUtils.d("看看数据C.."+entry.getValue());
                        carttonList.add(entry.getValue());
                    }
                }
                Collections.reverse(carttonList);

                LogUtils.d("看看数据D.."+carttonList);
                int anInt = SPStaticUtils.getInt(AppConstants.SWITCHKEY, 1);
                if (anInt == 1) {
                    carttonHistoryAdapter.replaceData(carttonList);
                }

            }
        });


        animeviewModel.getAllSLive().observe(this, new Observer<List<AnimePlayHistoryModel>>() {
            @Override
            public void onChanged(List<AnimePlayHistoryModel> animePlayHistoryModels) {

                animeList.clear();

                for (int i = 0; i < animePlayHistoryModels.size(); i++) {

                    if (animePlayHistoryModels.get(i).getType() == 1) {
                        animeMap.remove(animePlayHistoryModels.get(i).getTitlename());
                        animeMap.put(animePlayHistoryModels.get(i).getTitlename(), new
                                AnimeHistoryModel(animePlayHistoryModels.get(i).getName(), animePlayHistoryModels.get(i).getTitlename(),
                                animePlayHistoryModels.get(i).getPic(), animePlayHistoryModels.get(i).getUrl(),
                                animePlayHistoryModels.get(i).getSpeed(), animePlayHistoryModels.get(i).getType(), animePlayHistoryModels.get(i).getLryId()));
                    } else if (animePlayHistoryModels.get(i).getType() == 2) {
                        animeMap.remove(animePlayHistoryModels.get(i).getTitlename());
                        animeMap.put(animePlayHistoryModels.get(i).getTitlename(), new
                                AnimeHistoryModel(animePlayHistoryModels.get(i).getName(), animePlayHistoryModels.get(i).getTitlename(),
                                animePlayHistoryModels.get(i).getPic(), animePlayHistoryModels.get(i).getUrl(),
                                animePlayHistoryModels.get(i).getSpeed(), animePlayHistoryModels.get(i).getType(), animePlayHistoryModels.get(i).getYhid()));

                        LogUtils.d("啤啤虫宝宝S" + animePlayHistoryModels.get(i).getTitlename() + "---->" + animePlayHistoryModels.get(i).getName());
                    }


                }


                for (LinkedHashMap.Entry<String, AnimeHistoryModel> entry : animeMap.entrySet()) {
                    LogUtils.d("啤啤虫宝宝B" + entry.getValue());
                    animeList.add(entry.getValue());

                }
                Collections.reverse(animeList);

                animeHistoryAdapter.replaceData(animeList);

            }
        });

        carttonHistoryAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                CarttonHistoryModel item = (CarttonHistoryModel) adapter.getData().get(position);





                if (item.getType() == 1) {
                    Intent intent = new Intent(getActivity(), LRYCarttonReadingActivity.class);
                    intent.putExtra("lrychapterId", item.getLryId());
                    intent.putExtra("lryname", item.getName());
                    intent.putExtra("lrytitle", item.getTitleName());
                    intent.putExtra("lrypic",item.getPic());
//                    CartoonDataViewModel.getInstance().getLRYHistroryData().postValue(item.getLryListData());
                    startActivity(intent);
                } else if (item.getType() == 2) {
                    Intent intent = new Intent(getActivity(), KKCarttonReadingActivity.class);
                    intent.putExtra("kkCartoonId", item.getKkid());
                    intent.putExtra("kkname", item.getName());
                    CartoonDataViewModel.getInstance().getKKHistroryData().postValue(item.getKkListData());
                    startActivity(intent);
                }




            }
        });


        animeHistoryAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                AnimeHistoryModel item = (AnimeHistoryModel) adapter.getData().get(position);
                Intent intent = new Intent(getContext(), AnimePlayActivity.class);
                intent.putExtra("historyurl", item.getUrl());
                intent.putExtra("type", item.getType());
                if (item.getType() == 1) {
                    intent.putExtra("videoId", item.getLryId());
                } else if (item.getType() == 2) {
                    intent.putExtra("yhid", item.getYhid());
                }
                intent.putExtra("pic", item.getPic());
                intent.putExtra("titleName", item.getTitleName());
                startActivity(intent);
            }
        });

        functionAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                String item = (String) adapter.getData().get(position);

                if (position == 0) {

                    Intent intent = new Intent(getActivity(), ShareActivity.class);
                    startActivity(intent);
                } else if (position == 1) {
                    joinQQGroup("ocbvD4kiNy38TTLuagLVN5FqRweZtjkq");
                } else if (position == 2) {
                    ToastUtils.showLong("赞助APP 进群私聊群主");
                } else if (position == 3) {
                    SystemDialog systemDialog = new SystemDialog();
                    systemDialog.show(getChildFragmentManager(), "");
                } else if (position == 4) {

                } else if (position == 5) {

                }
            }
        });


        viewModelQQLogin.getQQName().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {

                if (TextUtils.isEmpty(s)) {
                    binding.tvName.setText("请先登录开锁更多功能");

                } else {
                    binding.tvName.setText("名称：" + s);
                }
            }
        });

        viewModelQQLogin.getAvatarUrl().observe(this, new Observer<Bitmap>() {
            @Override
            public void onChanged(Bitmap bitmap) {
                LogUtils.d("监听到" + bitmap);
                if (bitmap != null) {

                    binding.ivAvatar.setImageBitmap(bitmap);
                } else {

                    binding.ivAvatar.setImageResource(R.mipmap.avatar);
                }
            }
        });


        binding.ivAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), LoginActivity.class);
                startActivity(intent);
            }
        });
        binding.tvName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), LoginActivity.class);
                startActivity(intent);
            }
        });

    }

    @Override
    public void networkMessage() {

    }


    /****************
     *
     * 发起添加群流程。群号：Anime(931315646) 的 key 为： ocbvD4kiNy38TTLuagLVN5FqRweZtjkq
     * 调用 joinQQGroup(ocbvD4kiNy38TTLuagLVN5FqRweZtjkq) 即可发起手Q客户端申请加群 Anime(931315646)
     *
     * @param key 由官网生成的key
     * @return 返回true表示呼起手Q成功，返回false表示呼起失败
     ******************/
    public boolean joinQQGroup(String key) {
        Intent intent = new Intent();
        intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26jump_from%3Dwebapi%26k%3D" + key));
        // 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        try {
            startActivity(intent);
            return true;
        } catch (Exception e) {
            // 未安装手Q或安装的版本不支持
            return false;
        }
    }


    public void getTokenLogin() {

        JSONObject jsonObject = mTencent.loadSession(AppConstants.APP_ID);
        LogUtils.i(TAG, "initLocalData: " + jsonObject);
        if (jsonObject != null) {
            initOpenidAndToken(jsonObject);
            if (TextUtils.isEmpty(mTencent.getAccessToken())) {
                mTencent.initSessionCache(mTencent.loadSession(AppConstants.APP_ID));
            }
        }
        updateUserInfo();
    }

    public static void initOpenidAndToken(JSONObject jsonObject) {
        try {
            String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
            String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
            String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires)
                    && !TextUtils.isEmpty(openId)) {
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(openId);
            }
        } catch (Exception e) {
        }
    }

    private void updateUserInfo() {
        if (mTencent != null && mTencent.isSessionValid()) {
            IUiListener listener = new DefaultUiListener() {

                @Override
                public void onError(UiError e) {

                }

                @Override
                public void onComplete(final Object responsex) {
                    LogUtils.d(TAG, "updateUserInfo" + responsex);
                    JSONObject response = (JSONObject) responsex;
                    if (response.has("nickname")) {
                        try {

                            viewModelQQLogin.getQQName().setValue(response.getString("nickname"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    new Thread() {
                        @Override
                        public void run() {
                            JSONObject json = (JSONObject) response;
                            if (json.has("figureurl")) {
                                try {
                                    Bitmap bitmap = Util.getbitmap(json.getString("figureurl_qq_2"));
                                    binding.ivAvatar.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            viewModelQQLogin.getAvatarUrl().setValue(bitmap);
                                        }
                                    }, 100);
                                } catch (JSONException e) {
                                    SLog.e(TAG, "Util.getBitmap() jsonException : " + e.getMessage());
                                }

                            }
                        }
                    }.start();
                }

                @Override
                public void onCancel() {
                }
            };
            UserInfo info = new UserInfo(getActivity(), mTencent.getQQToken());
            info.getUserInfo(listener);
        }

    }
}
